package com.jinlejia.erp.ui.new_house.house;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.widget.HackyViewPager;
import com.weight.CustomToast;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

import uk.co.senab.photoview.PhotoView;



public class ViewPagerActivity extends AppCompatActivity {

    private ArrayList<String> imgs = new ArrayList<>();
    private int currentPosition = 0;
    private TextView count;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager2);
        if (getIntent().hasExtra("position")){
            currentPosition = getIntent().getIntExtra("position", 0);
        }
        imgs = getIntent().getStringArrayListExtra("imgs");
        String title = getIntent().getStringExtra("title");
        TextView tvTitle = findViewById(R.id.tvTitle);
        ViewPager mViewPager = (HackyViewPager) findViewById(R.id.view_pager);
        ImageView back = (ImageView) findViewById(R.id.id_back);
        TextView save = (TextView) findViewById(R.id.save_picture);
        count = (TextView) findViewById(R.id.count);
        count.setText( currentPosition+1 + "/" + imgs.size());
        tvTitle.setText(title);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new getImageCacheAsyncTask(ViewPagerActivity.this)
                        .execute(ApiConfig.MAGEHEADER_URL().concat(imgs.get(currentPosition)));
            }
        });

        mViewPager.setAdapter(new SamplePagerAdapter());
        mViewPager.setCurrentItem(currentPosition);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
                count.setText(position + 1 + "/" + imgs.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private class SamplePagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return imgs.size();
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            PhotoView photoView = new PhotoView(container.getContext());
            Glide.with(ViewPagerActivity.this).load(ApiConfig.MAGEHEADER_URL().concat(imgs.get(position))).placeholder(R.mipmap.ic_no_img).into(photoView);
//			photoView.setImageResource(sDrawables[position]);

            // Now just add PhotoView to ViewPager and return it
            container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }

    private class getImageCacheAsyncTask extends AsyncTask<String, Void, File> {
        private final Context context;

        public getImageCacheAsyncTask(Context context) {
            this.context = context;
        }

        @Override
        protected File doInBackground(String... params) {
            String imgUrl =  params[0];
            try {
                return Glide.with(context)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get();
            } catch (Exception ex) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {
            if (result == null) {
                return;
            }
            //此path就是对应文件的缓存路径
            String path = result.getPath();
            Bitmap bmp = BitmapFactory.decodeFile(path);
            if (bmp != null ){
                CustomToast.showToast(ViewPagerActivity.this,"保存成功",2000);
            }else {
                CustomToast.showToast(ViewPagerActivity.this,"保存失败",2000);
            }
            SavePicture(bmp);
        }

        private void SavePicture(Bitmap bitmap) {
            File appDir = new File(Environment.getExternalStorageDirectory(), "HouseTypePicture");//在SD卡中创建一个文件夹
            if (!appDir.exists()) {//如果该文件夹不存在，则创建一个文件夹
                appDir.mkdir();
            }
            try {
                String fileName = System.currentTimeMillis() + ".jpg";
                File file = new File(appDir, fileName);
                FileOutputStream out = null;
                out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG,100, out);
                out.flush();
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                ViewPagerActivity.this.sendBroadcast(intent);//这个广播的目的就是更新图库，发了这个广播进入相册就可以找到你保存的图片了！，记得要传你更新的file哦

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
